﻿using UnityEngine;
using System.Collections;
/// <summary>
/// 区别于itemMoveTarget 主要实现的功能是针对已经排好的队列重新进行位置平移
/// </summary>
public class ItemMoveTargetEx : MonoBehaviour {
	public Transform[] childs;
	public bool playNow = false;
	public Vector3 startPos;
	Vector3[] targetPos;	Transform cachedTransform;
	bool isPlaying;
	int _childCount;

	public float moveSpeed;
	public float saveTime;
	public float movedis;
	public float spacetime = 0.2f;
	[SerializeField]float moveTime = 1;
	void Awake(){
		cachedTransform = transform;
	}
	void Update(){
		if (playNow) {
			playNow = false;
			Play ();
		}	
		if (isPlaying) {
			for (int i = 0; i < _childCount; i++) {
				if (childs [i] != null) {

					float t = Mathf.Clamp ((Time.time - saveTime - i * spacetime) / moveTime, 0, 1);
					MoveChild (i, t);
					if (i == _childCount - 1 && t == 1) {
						isPlaying = false;
					}

				}
			}
		}
	}

	void MoveChild(int index,float time){
		Vector3 pos;
		Vector3 statpos = targetPos [index];
		Vector3 endpos = targetPos [index];
		statpos.y += movedis;
		pos = Vector3.Lerp (statpos, endpos, time);
		childs [index].transform.localPosition = pos;
	}
	public void Play(){
		saveTime = Time.time;
		_childCount = cachedTransform.childCount;
		childs = new Transform[_childCount];
		targetPos = new Vector3[_childCount];

		for (int i = 0; i < _childCount; i++) {
			childs [i] = cachedTransform.GetChild (i);
			targetPos [i] = childs [i].localPosition;
		}
		float space = (childs [0].localPosition.y - childs [childs.Length - 1].localPosition.y)/_childCount; 
		movedis = childs [0].localPosition.y - childs [childs.Length - 1].localPosition.y + space*2;
		for(int i = 0;i<_childCount;i++){
			SetChildPosY(targetPos[i].y+movedis,i);
		}

		isPlaying = true;
	}
	void SetChildPosY(float value,int id){
		Vector3 v = childs [id].localPosition;
		v.y = value;
		childs [id].localPosition = v;
	}
	public void UpdateMove(){
		
	}
}
